// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package adwords.axis.v201209.misc;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201209.cm.Campaign;
import com.google.api.ads.adwords.axis.v201209.cm.CampaignPage;
import com.google.api.ads.adwords.axis.v201209.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201209.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.jaxb.v201209.DownloadFormat;
import com.google.api.ads.adwords.lib.jaxb.v201209.ReportDefinition;
import com.google.api.ads.adwords.lib.jaxb.v201209.ReportDefinitionDateRangeType;
import com.google.api.ads.adwords.lib.jaxb.v201209.ReportDefinitionReportType;
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;
import com.google.api.ads.adwords.lib.utils.v201209.ReportDownloader;
import com.google.api.ads.common.lib.utils.Streams;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

/**
 * This example demonstrates how to authenticate using OAuth2.  This example
 * is meant to be run from the command line and requires user input.
 *
 * @author Kevin Winter
 */
public class OAuth2Example {

  private static final String SCOPE = "https://adwords.google.com/api/adwords";

  // This callback URL will allow you to copy the token from the success screen.
  private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";

  // If you do not have a client ID or secret, please create one in the
  // API console: https://code.google.com/apis/console#access
  private static final String CLIENT_ID = "INSERT_CLIENT_ID_HERE";
  private static final String CLIENT_SECRET = "INSERT_CLIENT_SECRET_HERE";

  private static Credential getOAuth2Credential() throws Exception {
    GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
        new NetHttpTransport(),
        new JacksonFactory(),
        CLIENT_ID,
        CLIENT_SECRET,
        Lists.newArrayList(SCOPE))
        .setApprovalPrompt("force")
        // Set the access type to offline so that the token can be refreshed.
        .setAccessType("offline").build();

    String authorizeUrl =
        authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
    System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');

    // Wait for the authorization code.
    System.out.println("Type the code you received here: ");
    String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // Create the OAuth2 credential request using the authorization code.
    GoogleAuthorizationCodeTokenRequest tokenRequest =
        authorizationFlow.newTokenRequest(authorizationCode);
    tokenRequest.setRedirectUri(CALLBACK_URL);
    GoogleTokenResponse tokenResponse = tokenRequest.execute();

    // Create the credential.
    Credential credential = authorizationFlow.createAndStoreCredential(tokenResponse, "");

    // Though not necessary when first created, you can refresh the token,
    // which is necessary after 60 minutes. In an offline application, you
    // should keep a reference to your credential to refresh it in this
    // time period.
    credential.refreshToken();

    return credential;
  }

  public static void runExample(
      AdWordsServices adWordsServices, AdWordsSession session, String reportFile) throws Exception {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    // Create selector.
    Selector selector = new Selector();
    selector.setFields(new String[] {"Id", "Name"});

    // Get all campaigns.
    CampaignPage page = campaignService.get(selector);

    // Display campaigns.
    if (page.getEntries() != null) {
      for (Campaign campaign : page.getEntries()) {
        System.out.println("Campaign with name \"" + campaign.getName() + "\" and id \""
            + campaign.getId() + "\" was found.");
      }
    } else {
      System.out.println("No campaigns were found.");
    }

    // Create selector.
    com.google.api.ads.adwords.lib.jaxb.v201209.Selector reportSelector =
        new com.google.api.ads.adwords.lib.jaxb.v201209.Selector();
    reportSelector.getFields().addAll(Lists.newArrayList(
        "CampaignId",
        "AdGroupId",
        "Id",
        "CriteriaType",
        "Criteria",
        "Impressions",
        "Clicks",
        "Cost"));

    // Create report definition.
    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
    reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
    reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
    reportDefinition.setDownloadFormat(DownloadFormat.CSV);
    // Enable to allow rows with zero impressions to show.
    reportDefinition.setIncludeZeroImpressions(true);
    reportDefinition.setSelector(reportSelector);

    ReportDownloadResponse response =
        new ReportDownloader(session).downloadReport(reportDefinition);
    if (response.getHttpStatus() == HttpURLConnection.HTTP_OK) {
      FileOutputStream fos = new FileOutputStream(new File(reportFile));
      Streams.copy(response.getInputStream(), fos);
      fos.close();
      System.out.println("Report successfully downloaded: " + reportFile);
    } else {
      System.out.println("Report was not downloaded. " + response.getHttpStatus() + ": "
          + response.getHttpResponseMessage());
    }
  }

  public static void main(String[] args) throws Exception {
    if (CLIENT_ID.equals("INSERT_CLIENT_ID_HERE")
        || CLIENT_SECRET.equals("INSERT_CLIENT_SECRET_HERE")) {
      throw new IllegalArgumentException("Please input your client IDs or secret. "
          + "See https://code.google.com/apis/console#access");
    }

    // Get the OAuth2 credential.
    Credential credential = getOAuth2Credential();

    // Construct a AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(credential)
        .build();

    AdWordsServices adWordsServices = new AdWordsServices();

    // Location to download report to.
    String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";

    runExample(adWordsServices, session, reportFile);
  }
}
